const echarts = require('echarts');
const Canvas = require('canvas');
const Path = require('path');
const fs = require('fs');

Canvas.registerFont(Path.join(__dirname, 'heiti.ttc'), {family: 'heiti'});

let ctx = Canvas.createCanvas(1, 1);
echarts.setCanvasCreator(() => ctx);

/**
 *
 * @param option
 * @param path
 * @param file
 */
module.exports = ({option, path, file}) => {
  let _file = Path.join(path, file);
  let _smallFile = Path.join(path, file + '_small');
  MyCanvas({
    option,
    width: 800,
    height: 500,
    //If the path  is not set, return the Buffer of image.
    file: _file, // Path is filepath of the image which will be created.
    smallFile: _smallFile,
  });
};

function MyCanvas(config) {
  let chart, option = {
    title: {
      text: 'test',
    },
    tooltip: {},
    legend: {
      data: ['test'],
    },
    xAxis: {
      data: ['a', 'b', 'c', 'd', 'f', 'g'],
    },
    yAxis: {},
    series: [
      {
        name: 'test',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20],
      }],
  };
  config.option = config.option || option;
  config.option.backgroundColor = '#ffffff';

  config.option.animation = false;
  let canvas = Canvas.createCanvas(parseInt(config.width, 10),
      parseInt(config.height, 10));
  chart = echarts.init(canvas);
  chart.setOption(config.option);
  fs.writeFileSync(config.file, canvas.toBuffer());
  if (!fs.existsSync(config.smallFile))
    fs.link(config.file, config.smallFile, () => {
    });
}